package net.qunzhi.modules.historyspider;

import cn.edu.hfut.dmic.webcollector.model.CrawlDatums;
import cn.edu.hfut.dmic.webcollector.model.Page;
import cn.edu.hfut.dmic.webcollector.plugin.berkeley.BreadthCrawler;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.qunzhi.common.utils.Constant;
import net.qunzhi.modules.cms.entity.TbElectricityStateEntity;
import net.qunzhi.modules.cms.entity.TbEquipmentEntity;
import net.qunzhi.modules.cms.entity.TbFlowStateEntity;
import net.qunzhi.modules.cms.service.SpiderService;
import net.qunzhi.modules.cms.service.TbElectricityStateService;
import net.qunzhi.modules.cms.service.TbEquipmentService;
import net.qunzhi.modules.cms.service.TbFlowStateService;
import net.qunzhi.modules.historyspider.client.xiParse;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/*
*  created by cq 2019/10/24
*/
@Service
public class ElectricitySpiderCrawler extends BreadthCrawler {
    @Autowired private SpiderService spiderService  = new SpiderService();
//    @PostConstruct
//    public void init() {
//        electricitySpiderCrawler = this;
//    }

    private static String crawlPath = "d://waterNetwork/spider/flowCraws";

    public ElectricitySpiderCrawler() {
        // 设置断点路径
        super(crawlPath, false);

        //设置线程数,根据需求来搞
        setThreads(4);
        //  设置断点重启
        setResumable(false);
        this.getConf().setConnectTimeout(30000);
        this.getConf().setReadTimeout(30000);
        //添加正则表达式规则
        regexRule.addRule("http://.*");
    }

    @Override
    public void visit(Page page, CrawlDatums crawlDatums) {
        LocalDateTime now = LocalDateTime.now();
        List<TbEquipmentEntity> equipmentList = spiderService.getEquipmentList();
        ArrayList<TbElectricityStateEntity> electricityStateEntities = new ArrayList<>();
        equipmentList.forEach(entity -> {
            if (StringUtils.isNotBlank(entity.getElectricTag())) {
                String imgName = page.html().split("document.all." + entity.getElectricTag() + ".innerHTML=")[1].substring(10, 28);
                TbElectricityStateEntity electricityStateEntity = new TbElectricityStateEntity();
                electricityStateEntity.setEquipmentId(entity.getId()).setTime(now).setStatus(Constant.ElectricStatus.getCodeByImgName(imgName));
                electricityStateEntities.add(electricityStateEntity);
            }
        });
        spiderService.insertElectricityState(electricityStateEntities);

    }
}